<template>
	<SkeletonScreen v-if="loading"></SkeletonScreen>
	<view style="position: fixed;top: 10rpx; z-index: 100; width: 100%;height: 80rpx; background-color: #000000;">
		<my-scroll-navbar @TagIndex="onnavIndex" :list="navIndexValue" :isNav="false"
			:isIcon="false"></my-scroll-navbar>
	</view>

	<view style="position: relative;top: 100rpx; color: aqua; z-index: 1000;">authUrls:{{authUrls}}</view>
	<view style="position: relative;top: 100rpx; color: aqua; z-index: 1000;">Code:{{codes}}</view>
	<view style="position: relative;top: 100rpx; color: aqua; z-index: 1000;">OpenId:{{code}}</view>

	<scroll-view style="margin-top: 100rpx;" @scrolltolower="onBottumLoadingA" class="swiper-topic-list"
		scroll-y="true">
		<view class="img-three">
			<view class="image-eight-Three">
				<my-img-y-Three class="item" v-for="item in ImgPlayValue" :images="item.imageUrl" :name="item.name"
					:biao="item.tagsName" :episode="item.episode" :episodes="item.episode" :urlId="item.id"
					:urlName="'/pages/of_play/play/play?'"></my-img-y-Three>
			</view>
		</view>

		<view style="display: flex; justify-content: center; align-items: center; padding: 30rpx 0; color: #464646;">
			<view>到此为止...</view>
		</view>
	</scroll-view>
</template>

<script setup>
	import {
		ref,
		onMounted
	} from 'vue';
	import {
		wechatAuth
	} from '@/API/wechatAuth.js';
	import {
		newVideosList,
		newVideosUrl,
		newTagsIndex,
		collectionPlay,
		updadeVideosCreate
	} from '@/API/ofPlayApis.js';

	const code = ref('');
	const codes = ref('');
	const authUrls = ref('')

	// 获取微信授权code
	async function getWechatCode() {
		console.log('[DEBUG] 开始微信授权流程');
		console.log('[DEBUG] 当前完整URL:', window.location.href);
		const urlParams = new URLSearchParams(window.location.search);
		console.log('[DEBUG] 当前URL参数:', window.location.search);

		// 显示当前URL信息（调试用）
		setTimeout(() => {
			uni.showToast({
				title: '检查URL参数中...',
				icon: 'none',
				duration: 1500
			});
		}, 500);

		const urlCode = urlParams.get('code');
		console.log('[DEBUG] 从URL获取的code:', urlCode);

		if (urlCode) {
			console.log('[DEBUG] 从URL获取到code:', urlCode);
			codes.value = urlCode;
			await sendCodeToBackend(urlCode);
		} else {
			console.log('[DEBUG] 未检测到code，准备跳转授权');
			const appId = 'wx168dbec792944e0d';
			// 确保与公众号后台配置的域名完全一致
			const redirectUri = encodeURIComponent('https://min.erkantv.cn/pages/index/index');
			console.log('[DEBUG] 编码后的redirectUri:', redirectUri);
			const authUrl =
				`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirectUri}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect`;
			// 验证URL格式是否正确
			console.log('[DEBUG] 检查授权URL格式:',
				authUrl.includes('scope=snsapi_base') &&
				authUrl.includes('#wechat_redirect'));
			console.log('[DEBUG] 授权跳转URL:', authUrl);
			authUrls.value = authUrl;
			// 显示授权确认对话框
			uni.showModal({
				title: '微信授权',
				content: '需要获取您的微信授权才能继续使用，是否前往授权？',
				confirmText: '去授权',
				cancelText: '取消',
				success: function(res) {
					if (res.confirm) {
						console.log('[DEBUG] 用户确认授权，准备跳转');
						// 保存当前页面URL，用于授权后返回
						try {
							uni.setStorageSync('auth_redirect_before', window.location.href);
						} catch (e) {
							console.error('[ERROR] 保存跳转前URL失败:', e);
						}
						// 跳转到微信授权页
						window.location.href = authUrl;
					} else {
						console.log('[DEBUG] 用户取消授权');
						uni.showToast({
							title: '您取消了授权，部分功能可能无法使用',
							icon: 'none',
							duration: 2000
						});
					}
				}
			});
		}
	}

	// 发送code到后端
	async function sendCodeToBackend(code) {
		codes.value = code;
		try {
			console.log('[DEBUG] 发送code到后端:', code);
			const res = await wechatAuth({
				code
			});
			console.log('[DEBUG] 后端返回结果:', res);

			if (res && res.openid) {
				uni.showToast({
					title: '登陆成功！',
					icon: 'none'
				});
				console.log('获取的openid:', res.openid);
				code.value = res.openid;
				uni.setStorageSync('user', {
					openId: res.openid
				}); // 存储openid
			} else {
				console.error('[ERROR] 后端未返回openid:', res);
				uni.showModal({
					title: '授权异常',
					content: '未获取到用户信息，请重试',
					showCancel: false
				});
			}
		} catch (error) {
			console.error('[ERROR] 授权失败:', error);
			uni.showModal({
				title: '授权失败',
				content: '请检查网络连接后重试',
				showCancel: false
			});
		}
	}
	const navIndexValue = ref([]);
	const PlayPageNum = ref(1) //筛选下一页
	const onaNavTagsIndex = ref(0);
	const ImgPlayValue = ref([])
	const loading = ref(true)
	// 获取筛选导航栏数据
	const onNavIndexFunction = async () => {
		let res = await newTagsIndex();
		console.log("tags:", res);
		navIndexValue.value = res;

	}
	onNavIndexFunction();
	// 筛选导航栏
	function onnavIndex(e) {
		console.log(e.item.sortId);
		onaNavTagsIndex.value = e.item.sortId;
		ImgPlayValue.value = [];
		PlayPageNum.value = 1;
		collectionPlayFunction(1, e.item.sortId);
	}
	// 获取筛选短剧信息
	const collectionPlayFunction = async (pageNum, tags) => {
		let res = await collectionPlay(pageNum, 16, tags);
		console.log("video数据:", res);
		// 创建一个 Set 来记录已存在的 id
		const existingIds = new Set(ImgPlayValue.value.map(item => item.id));
		// 过滤 res.list，只添加 id 不存在于 existingIds 中的项
		const newItems = res.list.filter(item => !existingIds.has(item.id));
		// 合并更新
		ImgPlayValue.value = ImgPlayValue.value.concat(newItems);
		PlayPageNum.value = res.nextPage;
		loading.value = false
	}
	collectionPlayFunction(PlayPageNum.value, onaNavTagsIndex.value);
	// 推荐页面触底函数
	function onBottumLoadingA() {
		console.log("PlayPageNum.value", PlayPageNum.value);
		if (PlayPageNum.value > 1) {
			collectionPlayFunction(PlayPageNum.value, onaNavTagsIndex.value);
			console.log("触底了scroll")
		}
	}

	onMounted(() => {
		console.log('[DEBUG] 页面加载，当前URL:', window.location.href);

		// 显示当前页面URL（调试用）
		setTimeout(() => {
			// 检查URL中是否包含code参数
			const urlParams = new URLSearchParams(window.location.search);
			const hasCode = urlParams.has('code');

			uni.showModal({
				title: '页面加载信息',
				content: `当前URL: ${window.location.href.substring(0, 50)}...

URL包含code参数: ${hasCode}`,
				showCancel: false
			});
		}, 1000);

		// 检查是否已有openid，避免重复授权
		const userInfo = uni.getStorageSync('user');
		if (userInfo && userInfo.openId) {
			console.log('[DEBUG] 已有openid，无需重新授权:', userInfo.openId);
			code.value = userInfo.openId;

			// 显示已登录状态
			setTimeout(() => {
				uni.showToast({
					title: '已登录',
					icon: 'success',
					duration: 1500
				});
			}, 1500);
		} else {
			console.log('[DEBUG] 未找到openid，开始授权流程');
			getWechatCode();
		}
	});
</script>